﻿using RWSBeeldbank.Common;
using RWSBeeldbank.Data;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using RWSBeeldbank.DataModel;
using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel.Resources;

// The Group Detail Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234229 

namespace RWSBeeldbank
{
    /// <summary>
    /// A page that displays an overview of a single group, including a preview of the items
    /// within the group.
    /// </summary>
    public sealed partial class SearchResults : LayoutAwarePage
    {
        public String queryStringText = "";
        
        //public MediaObjectDataSource _MediaItems;
        private UIElement _previousContent;
        private ApplicationExecutionState _previousExecutionState;

        public SearchResults()
        {
            this.InitializeComponent();
        }
        
        /// <summary>
        /// Determines how best to support navigation back to the previous application state.
        /// </summary>
        public static void Activate(String queryTextString, ApplicationExecutionState previousExecutionState)
        {
            var previousContent = Window.Current.Content;
            var frame = previousContent as Frame;

            if (frame != null)
            {
                // If the app is already running and uses top-level frame navigation we can just
                // navigate to the search results
                frame.Navigate(typeof(SearchResults), queryTextString);
            }
            else
            {
                // Otherwise bypass navigation and provide the tools needed to emulate the back stack
                SearchResults page = new SearchResults();
                page._previousContent = previousContent;
                page._previousExecutionState = previousExecutionState;
                page.LoadState(queryTextString, null);
                Window.Current.Content = page;
            }

            // Either way, active the window
            Window.Current.Activate();
        }
        
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The
        /// Parameter property provides the group to be displayed.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            var queryTextString = e.Parameter as String;

            // Communicate results through the view model
            var resourceLoader = new ResourceLoader();

            if (e.NavigationMode == NavigationMode.New)
            {
                // clear all items in the current search group
                MediaObjectDataSource._mediaObjectDataSource.AllGroups.FirstOrDefault(c => c.UniqueId.Equals(Constants.SEARCHCOLLECTIONID)).Items.Clear();
            }

            CollectionViewSource dynamicMediaItems = (CollectionViewSource)LayoutRoot.Resources["dynamicMediaItems"];
            dynamicMediaItems.Source = MediaObjectDataSource._mediaObjectDataSource.DynamicLoadItemsSearch(queryTextString);

            resultText.Text = resourceLoader.GetString("SearchResultText");
            queryText.Text = " " + '\u201c' + queryTextString + '\u201d';
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            var queryTextString = navigationParameter as String;

            // Communicate results through the view model
            var resourceLoader = new ResourceLoader();

            var group = MediaObjectDataSource.GetGroup((String)navigationParameter);
            this.DefaultViewModel["Group"] = group;

            CollectionViewSource dynamicMediaItems = (CollectionViewSource)LayoutRoot.Resources["dynamicMediaItems"];
            dynamicMediaItems.Source = MediaObjectDataSource._mediaObjectDataSource.DynamicLoadItemsSearch(queryTextString);

            resultText.Text = resourceLoader.GetString("SearchResultText");
            queryText.Text = " " + '\u201c' + queryTextString + '\u201d';
        }

        /// <summary>
        /// Invoked when an item is clicked.
        /// </summary>
        /// <param name="sender">The GridView (or ListView when the application is snapped)
        /// displaying the item clicked.</param>
        /// <param name="e">Event data that describes the item clicked.</param>
        void ItemView_ItemClick(object sender, ItemClickEventArgs e)
        {
            // Navigate to the appropriate destination page, configuring the new page
            // by passing required information as a navigation parameter
            var mediaObjectId = (MediaObjectDataItem)e.ClickedItem;

            var itemId = mediaObjectId.UniqueId;

            switch (mediaObjectId.TypeId)
            {
                case Constants.ITEM_TYPE_VIDEO:
                    this.Frame.Navigate(typeof(VideoDetailPage), itemId);
                    break;
                case Constants.ITEM_TYPE_DIGITAL:
                    this.Frame.Navigate(typeof(DigitalItemDetailPage), itemId);
                    break;
                default:
                    this.Frame.Navigate(typeof(ItemDetailPage), itemId);
                    break;
            }
        }

        // Start invalidate cache 
        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {            
            if (e.NavigationMode == NavigationMode.Back)
            {
                // Add a Frame control to the window
                var rootFrame = new Frame();
                SuspensionManager.RegisterFrame(rootFrame, "AppFrame");

                // Place the frame in the current Window and ensure that it is active
                Window.Current.Content = rootFrame;

                if (!rootFrame.Navigate(typeof(GroupedItemsPage), "AllGroups"))
                    throw new Exception("Failed to create initial page");
            }
        }

        private void ResetPageCache()
        {
            var cacheSize = ((Frame)Parent).CacheSize;
            ((Frame)Parent).CacheSize = 0;
            ((Frame)Parent).CacheSize = cacheSize;
        }

    }
}
